import React, { useState, useRef } from 'react';
import styles from './ButtonStyle.module.css';

const ButtonStyle = () => {
    const [buttonStyle, setButtonStyle] = useState({
        background: '#ffffff',
        color: '#000000',
        borderRadius: '0',
        borderColor: '#000000',
        borderWidth: '1px',
    });
    
    const [imageUrl, setImageUrl] = useState('');
    const [crop, setCrop] = useState();
    const [completedCrop, setCompletedCrop] = useState(null);
    const [isCropping, setIsCropping] = useState(false);
    const buttonRef = useRef(null);
    const imgRef = useRef(null);
    
    const handleImageUpload = (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = () => {
                setImageUrl(reader.result);
                setIsCropping(true); // 显示裁剪界面
            };
            reader.readAsDataURL(file);
        }
    };

    const onCropComplete = (crop, pixelCrop) => {
        setCompletedCrop(pixelCrop);
    };

    const getCroppedImg = () => {
        if (!completedCrop || !imgRef.current) return;

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const image = imgRef.current;

        canvas.width = completedCrop.width;
        canvas.height = completedCrop.height;

        ctx.drawImage(
            image,
            completedCrop.x,
            completedCrop.y,
            completedCrop.width,
            completedCrop.height,
            0,
            0,
            completedCrop.width,
            completedCrop.height
        );

        // 转换为 base64
        const base64Image = canvas.toDataURL('image/png');
        analyzeButtonStyle(base64Image);
        setIsCropping(false);
    };

    const analyzeButtonStyle = (imgUrl) => {
        const img = new Image();
        img.src = imgUrl;
        img.onload = () => {
            // 这里可以添加更复杂的图像分析逻辑
            // 目前仅作为示例
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
            
            // 获取中心点颜色作为背景色
            const centerX = Math.floor(img.width / 2);
            const centerY = Math.floor(img.height / 2);
            const pixel = ctx.getImageData(centerX, centerY, 1, 1).data;
            
            setButtonStyle(prev => ({
                ...prev,
                background: `rgb(${pixel[0]}, ${pixel[1]}, ${pixel[2]})`,
            }));
        };
    };

    const generateCSS = () => {
        const baseStyle = {
            boxSizing: 'border-box',
            height: 'fit-content',
            width: 'fit-content',
            lineHeight: '1.5',
            padding: '2px 4px',
            fontSize: '12px',
            ...buttonStyle,
            border: `${buttonStyle.borderWidth} solid ${buttonStyle.borderColor}`,
        };

        return Object.entries(baseStyle)
            .map(([key, value]) => `${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`)
            .join('\n');
    };

    const copyToClipboard = (text) => {
        navigator.clipboard.writeText(text)
            .then(() => alert('CSS代码已复制到剪贴板！'))
            .catch(err => console.error('复制失败：', err));
    };

    return (
        <div className={styles.container}>
            <div className={styles.uploadSection}>
                <input 
                    type="file" 
                    accept="image/*" 
                    onChange={handleImageUpload}
                    className={styles.fileInput}
                />
            </div>

            {isCropping && imageUrl && (
                <div className={styles.cropSection}>
                    <h3>请框选按钮区域</h3>
                    <ReactCrop
                        crop={crop}
                        onChange={c => setCrop(c)}
                        onComplete={onCropComplete}
                        aspect={undefined}
                    >
                        <img
                            ref={imgRef}
                            src={imageUrl}
                            style={{ maxWidth: '100%' }}
                            alt="上传图片"
                        />
                    </ReactCrop>
                    <button 
                        onClick={getCroppedImg}
                        className={styles.cropButton}
                        disabled={!completedCrop}
                    >
                        确认裁剪
                    </button>
                </div>
            )}

            {!isCropping && imageUrl && (
                <div className={styles.designSection}>
                    {/* 原图预览 */}
                    <div className={styles.originalImage}>
                        <h3>原始按钮</h3>
                        <img src={imageUrl} alt="原始按钮" />
                    </div>

                    {/* 调整和预览区域 */}
                    <div className={styles.adjustPreview}>
                        <div className={styles.previewSection}>
                            <h3>按钮预览</h3>
                            <div className={styles.previewWrapper}>
                                <img 
                                    src={imageUrl} 
                                    alt="背景图"
                                    className={styles.backgroundImage}
                                />
                                <button
                                    ref={buttonRef}
                                    style={{
                                        ...buttonStyle,
                                        boxSizing: 'border-box',
                                        height: 'fit-content',
                                        width: 'fit-content',
                                        lineHeight: '1.5',
                                        padding: '2px 4px',
                                        fontSize: '12px',
                                        border: `${buttonStyle.borderWidth} solid ${buttonStyle.borderColor}`,
                                        position: 'relative',
                                        zIndex: 1,
                                    }}
                                >
                                    预览按钮
                                </button>
                            </div>
                        </div>

                        <div className={styles.controlSection}>
                            <div className={styles.controlItem}>
                                <label>背景色：</label>
                                <input 
                                    type="color" 
                                    value={buttonStyle.background}
                                    onChange={(e) => setButtonStyle(prev => ({
                                        ...prev,
                                        background: e.target.value
                                    }))}
                                />
                            </div>

                            <div className={styles.controlItem}>
                                <label>文字颜色：</label>
                                <input 
                                    type="color" 
                                    value={buttonStyle.color}
                                    onChange={(e) => setButtonStyle(prev => ({
                                        ...prev,
                                        color: e.target.value
                                    }))}
                                />
                            </div>

                            <div className={styles.controlItem}>
                                <label>边框圆角：</label>
                                <input 
                                    type="range" 
                                    min="0" 
                                    max="20"
                                    value={parseInt(buttonStyle.borderRadius)}
                                    onChange={(e) => setButtonStyle(prev => ({
                                        ...prev,
                                        borderRadius: `${e.target.value}px`
                                    }))}
                                />
                            </div>

                            <div className={styles.controlItem}>
                                <label>边框颜色：</label>
                                <input 
                                    type="color" 
                                    value={buttonStyle.borderColor}
                                    onChange={(e) => setButtonStyle(prev => ({
                                        ...prev,
                                        borderColor: e.target.value
                                    }))}
                                />
                            </div>

                            <div className={styles.controlItem}>
                                <label>边框宽度：</label>
                                <input 
                                    type="range" 
                                    min="0" 
                                    max="5"
                                    value={parseInt(buttonStyle.borderWidth)}
                                    onChange={(e) => setButtonStyle(prev => ({
                                        ...prev,
                                        borderWidth: `${e.target.value}px`
                                    }))}
                                />
                            </div>

                            <div className={styles.controlItem}>
                                <label>圆角调整：</label>
                                <div className={styles.radiusControls}>
                                    <div>
                                        <label>左上：</label>
                                        <input 
                                            type="range" 
                                            min="0" 
                                            max="50"
                                            value={parseInt(buttonStyle.borderTopLeftRadius || '0')}
                                            onChange={(e) => setButtonStyle(prev => ({
                                                ...prev,
                                                borderTopLeftRadius: `${e.target.value}px`
                                            }))}
                                        />
                                        <span>{buttonStyle.borderTopLeftRadius}</span>
                                    </div>
                                    <div>
                                        <label>右上：</label>
                                        <input 
                                            type="range" 
                                            min="0" 
                                            max="50"
                                            value={parseInt(buttonStyle.borderTopRightRadius || '0')}
                                            onChange={(e) => setButtonStyle(prev => ({
                                                ...prev,
                                                borderTopRightRadius: `${e.target.value}px`
                                            }))}
                                        />
                                        <span>{buttonStyle.borderTopRightRadius}</span>
                                    </div>
                                    <div>
                                        <label>左下：</label>
                                        <input 
                                            type="range" 
                                            min="0" 
                                            max="50"
                                            value={parseInt(buttonStyle.borderBottomLeftRadius || '0')}
                                            onChange={(e) => setButtonStyle(prev => ({
                                                ...prev,
                                                borderBottomLeftRadius: `${e.target.value}px`
                                            }))}
                                        />
                                        <span>{buttonStyle.borderBottomLeftRadius}</span>
                                    </div>
                                    <div>
                                        <label>右下：</label>
                                        <input 
                                            type="range" 
                                            min="0" 
                                            max="50"
                                            value={parseInt(buttonStyle.borderBottomRightRadius || '0')}
                                            onChange={(e) => setButtonStyle(prev => ({
                                                ...prev,
                                                borderBottomRightRadius: `${e.target.value}px`
                                            }))}
                                        />
                                        <span>{buttonStyle.borderBottomRightRadius}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            <div className={styles.codeSection}>
                <h3>生成的 CSS 代码</h3>
                <pre>{generateCSS()}</pre>
                <button 
                    onClick={() => copyToClipboard(generateCSS())}
                    className={styles.copyButton}
                >
                    复制 CSS
                </button>
            </div>
        </div>
    );
};

export default ButtonStyle;